<!--
  * 公司列表
  *
  * @Author:    1024创新实验室-主任：卓大
  * @Date:      2022-08-15 20:15:49
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
-->
<template>
    <!-- <a-form class="smart-query-form" v-privilege="'oa:enterprise:query'">
      <a-row class="smart-query-form-row">
        
  
        <a-form-item label="时间" class="smart-query-form-item">
          <a-space direction="vertical" :size="12">
            <a-range-picker v-model:value="searchDate" valueFormat="YYYY-MM-DD HH:mm:ss" :presets="defaultTimeRanges" @change="dateChange" />
          </a-space>
        </a-form-item>
        <a-form-item label="车牌" class="smart-query-form-item">
          <a-input style="width: 300px" v-model:value="queryForm.plate_num" placeholder="请输入车牌" />
        </a-form-item>
  
        <a-form-item class="smart-query-form-item smart-margin-left10">
          <a-button-group>
            <a-button type="primary" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-form-item>
      </a-row>
    </a-form> -->
  
    <a-card size="small" :bordered="false" :hoverable="true">
      <a-row class="smart-table-btn-block">
        <div class="smart-table-operate-block">
          <a-button @click="exportExcel()" v-privilege="'history:carRecord:exportExcel'" type="primary">
            <template #icon>
              <FileExcelOutlined />
            </template>
            导出
          </a-button>
        </div>
        <div class="smart-table-setting-block">
          <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.OA.ENTERPRISE" :refresh="ajaxQuery" />
        </div>
      </a-row>
      <a-table
        size="small"
        :dataSource="tableData"
        :columns="columns"
        :pagination="false"
        :loading="tableLoading"
        bordered
      >
        <template #bodyCell="{ column, record, text,index }">
          <template v-if="column.dataIndex === 'index'">
            {{ index+1 }}
          </template>
          <template v-if="column.dataIndex === 'isPass'">
              {{['禁止','通行','识别码作废'][text]}}
          </template>
          
        </template>
      </a-table>
  
      <div class="smart-query-table-page">
        <a-pagination
          showSizeChanger
          showQuickJumper
          show-less-items
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :defaultPageSize="queryForm.pageSize"
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :total="total"
          @change="ajaxQuery"
          @showSizeChange="ajaxQuery"
          :show-total="(total) => `共${total}条`"
        />
      </div>
      <!-- <EnterpriseOperate ref="operateRef" @refresh="ajaxQuery" /> -->
    </a-card>
  </template>
  <script setup>
    import { reactive, ref, onMounted } from 'vue';
    import { message, Modal } from 'ant-design-vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { enterpriseApi } from '/@/api/business/oa/enterprise-api';
    import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
    import { useRouter } from 'vue-router';
    // import EnterpriseOperate from './components/enterprise-operate-modal.vue';
    import { smartSentry } from '/@/lib/smart-sentry';
    import { defaultTimeRanges } from '/@/lib/default-time-ranges';
    import TableOperator from '/@/components/support/table-operator/index.vue';
    import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
    import {tagRecordApi} from '/@/api/licensePlate/history/tagRecord'
    import * as XLSX from 'xlsx';
    import { saveAs } from 'file-saver';
  
    // --------------------------- 企业表格 列 ---------------------------
  
    const columns = ref([
      {
        title: '序号',
        dataIndex: 'index',
        width: 50,
        align:'center'
      },
      {
        title: '标签号',
        dataIndex: 'tag',
      },
      {
        title: '车牌号',
        dataIndex: 'carPlate',
      },
      {
        title: '是否通行',
        dataIndex: 'isPass',
      },
      {
        title: '车辆通行时间',
        dataIndex: 'visitTime',
        // fixed: 'right',
      },
    ]);
  
    // --------------------------- 查询 ---------------------------
  
    const queryFormState = {
      pageNum: 1,
      pageSize: PAGE_SIZE,
      searchCount: true,
    };
    const queryForm = reactive({ ...queryFormState });
    const tableLoading = ref(false);
    const tableData = ref([]);
    const total = ref(0);
  
    // 日期选择
    const searchDate = ref();
  
    function dateChange(dates, dateStrings) {
      console.log(dateStrings);
      queryForm.startTime = dateStrings[0];
      queryForm.endTime = dateStrings[1];
    }
    // 查询
    function onSearch() {
      queryForm.pageNum = 1;
      ajaxQuery();
    }
    // 重置查询
    function resetQuery() {
      searchDate.value = [];
      Object.assign(queryForm, queryFormState);
      ajaxQuery();
    }
    function dateToSeconds(dateStr) {
      if (dateStr == "") {
        return ""
      }
      let date = new Date(dateStr);
      return date.getTime() / 1000;
    }
  
    async function ajaxQuery() {
      try {
        tableLoading.value = true;
        let responseModel = await tagRecordApi.getList(queryForm);
        const list = responseModel.data.list;
        total.value = responseModel.data.total;
        tableData.value = list;
      } catch (e) {
        smartSentry.captureError(e);
      } finally {
        tableLoading.value = false;
      }
    }
  
    // --------------------------- 导出 ---------------------------
    // exportTagRecord
    async function exportExcel() {
      try{
        // let queryObj = {
        //   tag:queryForm.plate_num,
        //   endTime:queryForm.endTime?moment(queryForm.endTime).valueOf():'',
        //   startTime:queryForm.startTime?moment(queryForm.startTime).valueOf():''
        // }
        let dataList = await tagRecordApi.exportTagRecord();
        console.log('dataList',dataList)
        let listExport = []
        listExport = dataList.map(item => ({
            车牌号码: item.plate_num,
            车牌底色: item.plate_color,
            车牌识别时间: item.start_time,
            相机IP: item.cam_ip,
        }));
        // 导出数据
        const ws = XLSX.utils.json_to_sheet(listExport);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
        const xlsxData = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
        const blob = new Blob([xlsxData], { type: 'application/octet-stream' });
        saveAs(blob, '标签通行记录.xlsx');
      } catch (err) {
        console.error(err);
      }
      
    }
    
    // --------------------------- 删除 ---------------------------
  
    function confirmDelete(enterpriseId) {
      Modal.confirm({
        title: '确定要删除吗？',
        content: '删除后，该信息将不可恢复',
        okText: '删除',
        okType: 'danger',
        onOk() {
          del(enterpriseId);
        },
        cancelText: '取消',
        onCancel() {},
      });
    }
  
    async function del(enterpriseId) {
      try {
        SmartLoading.show();
        await enterpriseApi.delete(enterpriseId);
        message.success('删除成功');
        ajaxQuery();
      } catch (e) {
        smartSentry.captureError(e);
      } finally {
        SmartLoading.hide();
      }
    }
  
    // --------------------------- 增加、修改、详情 ---------------------------
  
    let router = useRouter();
    const operateRef = ref();
    function add() {
      operateRef.value.showModal();
    }
  
    function update(enterpriseId) {
      operateRef.value.showModal(enterpriseId);
    }
  
    function detail(enterpriseId) {
      router.push({ path: '/oa/enterprise/enterprise-detail', query: { enterpriseId: enterpriseId } });
    }
  
    onMounted(ajaxQuery);
  </script>
  